package cn.liutao.common.utils;

import cn.liutao.common.enums.CommonEnum;
import io.jsonwebtoken.*;
import lombok.Data;
import java.util.Date;
/**
 * @author liutao
 * @Description JWTUtils
 * @date 2023/10/30 23:19
 * @Version 1.0
 */
@Data
public class JwtUtils {
    public long expire = Long.valueOf(CommonEnum.JWT_TOKEN_EXPIRE.getValue());
    public String secret = CommonEnum.JWT_TOKEN_SECRET.getValue();
    public String header = CommonEnum.JWT_TOKEN_HEADER.getValue();

    // 生成JWT
    public String generateToken(String username) {
        Date nowDate = new Date();
        Date expireDate = new Date(nowDate.getTime() + 1000 * expire);

        return Jwts.builder()
                .setHeaderParam("typ", "JWT")
                .setSubject(username)
                .setIssuedAt(nowDate)
                .setExpiration(expireDate)    // 1天过期
                .signWith(SignatureAlgorithm.HS512, secret)
                .compact();
    }

    // 解析JWT
    public Claims getClaimsByToken(String jwt) {
        try {
            return Jwts.parser()
                    .setSigningKey(secret)
                    .parseClaimsJws(jwt)
                    .getBody();
        } catch (Exception e) {
            return null;
        }
    }

    // 判断JWT是否过期
    public boolean isTokenExpired(Claims claims) {
        return claims.getExpiration().before(new Date());
    }

}
